package com.han.hotelplat.cms.controller.employee;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.allinpay.xmltrans.pojo.TranxCon;
import com.allinpay.xmltrans.service.TranxServiceImpl;
import com.han.hotelplat.comm.Constant;
import com.han.hotelplat.comm.ResponseWrapTo;
import com.han.hotelplat.comm.ResponseWrapTo.CodeType;
import com.han.hotelplat.comm.base.Pager;
import com.han.hotelplat.comm.utils.AreaHelp;
import com.han.hotelplat.comm.utils.HssfUtil;
import com.han.hotelplat.comm.utils.MD5;
import com.han.hotelplat.comm.utils.MsgHelp;
import com.han.hotelplat.comm.utils.RequestUtil;
import com.han.hotelplat.comm.utils.StrUtil;
import com.han.hotelplat.comm.utils.UUIDUtils;
import com.han.hotelplat.manager.LogManager;
import com.han.hotelplat.model.AreaModel;
import com.han.hotelplat.model.EmLogModel;
import com.han.hotelplat.pojo.cashextract.CashExtract;
import com.han.hotelplat.pojo.employee.Employee;
import com.han.hotelplat.pojo.log.Logger;
import com.han.hotelplat.pojo.systemuser.Systemuser;
import com.han.hotelplat.pojo.wallet.Wallet;
import com.han.hotelplat.service.bill.BillService;
import com.han.hotelplat.service.cashextract.CashExtractService;
import com.han.hotelplat.service.employee.EmployeeService;
import com.han.hotelplat.service.wallet.WalletService;

@Controller
@RequestMapping("/cms/employee")
public class CMSEmployeeController {
	
	@Autowired
	private EmployeeService emservice;
	
	@Autowired
	private WalletService walletService;
	
	@Autowired
	private LogManager logManager;
	
	@Autowired
	private CashExtractService cashExtractService;
	
	@Autowired
	private BillService billService;
	
	private TranxServiceImpl tranxService=new TranxServiceImpl();
	
	private boolean isfront=false;//是否发送至前置机（由前置机进行签名）如不特别说明，商户技术不要设置为true
	
	/**
	 * form表单提交 Date类型数据绑定 <功能详细描述>
	 * 
	 * @param binder
	 * @see [类、类#方法、类#成员]
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		
		//实现表单中的字符串自动转换为Date或者Timestamp 类型。
		//http://www.micmiu.com/j2ee/spring/springmvc-binding-date/
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// ("yyyy-MM-dd HH:mm:ss");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
		//binder.registerCustomEditor(java.sql.Timestamp.class, new CustomTimestampEditor(dateFormat, true));
	}
	
	/**
	 * 通知帮工补齐资料
		 * @description	
		 * @author  han1088
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "noticeEmAddInfo", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET, RequestMethod.POST })
	public String noticeEmAddInfo(){
		emservice.noticeEmAddInfo();
		return new ResponseWrapTo(CodeType.success, "发送成功", null).toJson();
	}
	/**
	 * 
		 * @description	
		 * @author  han1088
		 * @param cashIds 提现申请ID列表
		 * @param password 管理员密码
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "authEmCashExt", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET, RequestMethod.POST })
	public String authEmCashExt(String cashIds, String password){
		Systemuser user = (Systemuser) RequestUtil.getSessionAttribute(Constant.CMS_SESSION_LOGIN_USER);
		Integer pushCount = (Integer) RequestUtil.getSessionAttribute("pushCount");
		if(pushCount == null){
			pushCount = 0;
		}
		if(!user.getPassword().equals(MD5.toMD5(password))){
			if(pushCount >= 2){
				Enumeration<String> keys = RequestUtil.getSession().getAttributeNames();
				while (keys.hasMoreElements()) {
					String key = (String) keys.nextElement();
					RequestUtil.getSession().removeAttribute(key);
				}
				Cookie[] cookies = RequestUtil.getRequest().getCookies();
				for (Cookie cookie : cookies) {
					cookie.setMaxAge(0);
				}
				Subject currentUser = SecurityUtils.getSubject();
				currentUser.logout();
				return new ResponseWrapTo(CodeType.success, "用户退出成功", null).toJson();
			}else if(pushCount>=0 && pushCount<3){
				RequestUtil.setSessionAttribute("pushCount",pushCount+1);
				return new ResponseWrapTo(-1, "密码错误,请重新输入。剩余"+(2-pushCount)+"次验证，输入错误将会退出登陆", null).toJson();
			}
		}
		RequestUtil.setSessionAttribute("pushCount",0);
		JSONArray ids = JSONArray.parseArray(cashIds);
		List<CashExtract> li = new ArrayList<CashExtract>();
		float sumMoney = 0;
		for(Object idJs : ids ){
			int id = JSONObject.parseObject(idJs.toString()).getIntValue("id");
			CashExtract ce = cashExtractService.findCashExById(id);
			if(ce.getState().intValue() != Constant.CE_STATE_CREAT.intValue()
					&& ce.getState().intValue() != Constant.CE_STATE_FAIL.intValue()){//已经处理过的跳过
				continue;
			}
			float money = ce.getMoney()*100;//通联以分为单位
			sumMoney = sumMoney + money; 
			li.add(ce);
		}
		//查询账户余额
		int balance = tranxService.acctInfo(TranxCon.tranURL, isfront, Constant.acctNo,Constant.pfxPath,Constant.tltcerPath);
		
		//余额不足
		if(sumMoney > balance){
			return new ResponseWrapTo(-3, "提现失败账户余额不足，当前账户余额："+(balance/100), null).toJson();
		}
		
		for(CashExtract ce : li ){
			double money = ce.getMoney()*100;//通联以分为单位
			Double m = Double.parseDouble(money+"");
			String bankcard = ce.getBankcard();
			JSONObject card = JSONObject.parseObject(bankcard);
			String accno = card.getString("bankcardno");
			String bankcode = card.getString("bankcode");
			Employee em = emservice.getEmployee(ce.getUserid());
			try {
				Map<String, Object> re = tranxService.singleTranx(TranxCon.tranURL, isfront, em.getRealname(), 
						accno, m.intValue()+"", bankcode, ce.getTel(), ce.getSerial(),Constant.pfxPath,Constant.tltcerPath );
				int code = (int) re.get("code");
				String message = (String) re.get("message");
				String req_sn  = (String) re.get("req_sn");
				if(code == 0){
					CashExtract oldce = cashExtractService.findCashExById(ce.getId());
					oldce.setEdittime(new Date());
					oldce.setState(Constant.CE_STATE_SUCCESS);
					oldce.setRemark(oldce.getRemark()==null?"":oldce.getRemark()+";"+message);
					oldce.setAuthuserid(user.getUserid());
					oldce.setReqsn(req_sn);
					cashExtractService.update(oldce);
					Wallet w = walletService.getWallet(oldce.getUserid());
					//如果提现成功要修改流水记录里面的状态
					billService.updateBill(w.getId(), oldce.getId()+"="+Constant.CE_STATE_CREAT);
				}else if(code ==1){//需要发起查询的提现请求
					CashExtract oldce = cashExtractService.findCashExById(ce.getId());
					oldce.setReqsn(req_sn);
					oldce.setEdittime(new Date());
					oldce.setState(Constant.CE_STATE_WAIT_QUERY);
					oldce.setAuthuserid(user.getUserid());
					oldce.setRemark(oldce.getRemark()==null?"":oldce.getRemark()+";"+message);
					cashExtractService.update(oldce);
				}else if(code ==-3){//超过了通联可以提现的时间
					CashExtract oldce = cashExtractService.findCashExById(ce.getId());
					oldce.setEdittime(new Date());
					oldce.setAuthuserid(user.getUserid());
					oldce.setRemark(oldce.getRemark()==null?"":oldce.getRemark()+";提现失败："+message);
					cashExtractService.update(oldce);
					return new ResponseWrapTo(code, message, null).toJson();
				}else{
					CashExtract oldce = cashExtractService.findCashExById(ce.getId());
					oldce.setReqsn(req_sn);
					oldce.setEdittime(new Date());
					oldce.setState(Constant.CE_STATE_FAIL);
					oldce.setAuthuserid(user.getUserid());
					oldce.setRemark(oldce.getRemark()==null?"":oldce.getRemark()+";提现失败："+message);
					cashExtractService.update(oldce);
					//失败后恢复额度
					Wallet w = walletService.getWallet(oldce.getUserid());
					String taskId = oldce.getId().toString()+"="+Constant.CE_STATE_FAIL;//提现申请的ID=状态
					billService.creatBill(null, w.getId(), oldce.getMoney()+1, 
							Constant.BILL_TYPE_CASH,"提现失败", taskId, null, Constant.CHARGE_CHANNEL_TRANSFER,
							"转账系统");
				}
			}catch (Exception e){
				e.printStackTrace();
				return new ResponseWrapTo(-3, "系统异常", null).toJson();
			}
		}
		return new ResponseWrapTo(0, "提现申请提交银行成功", null).toJson();
	}
	
	/**
	 * 
		 * @description	
		 * @author  han1088
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "exportCashExList", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET, RequestMethod.POST })
	public void exportCashExList(HttpServletResponse resp, HttpServletRequest req,String startDate, String endDate,Integer state, Integer sortType,
			Integer areaCode, String condition){
		List<CashExtract> data = cashExtractService.exportCashExList( startDate,  endDate, state,  sortType,
				 areaCode,  condition);
		String filename = "帮工提现记录.xls";
		resp.setHeader("Content-Type", "application/octet-stream");
		try {
			resp.setHeader("Content-Disposition", "attachment;filename=" + HssfUtil.buildAttachmentFileName(req, filename));
			List<Object[]> datas = new ArrayList<Object[]>();
			String[] columnNames = new String[] { "提现单号","创建时间","姓名","手机号","所在地区","银行名称","银行卡号","提现金额","提现状态"};
			for(CashExtract ce : data){
				Object[] dataObj = new Object[columnNames.length];
				dataObj[0] = ce.getSerial();
				dataObj[1] = ce.getCreattime();
				dataObj[2] = ce.getRealname();
				dataObj[3] = ce.getTel();
				String address = "";
				if(ce.getArea() != null){
					AreaModel[] area = AreaHelp.getInstance().getAreaModels(ce.getArea().toString());
					for(AreaModel a:area){
						address = address+a.getName();
					}
				}
				dataObj[4] = address;
				JSONObject bancard = JSONObject.parseObject(ce.getBankcard());
				if(bancard != null){
					dataObj[5] = bancard.get("banktype");
					dataObj[6] = bancard.get("bankno");
				}else{
					dataObj[5] = "";
					dataObj[6] = "";
				}
				
				dataObj[7] = ce.getMoney();
				if(ce.getState().intValue() == Constant.CE_STATE_CREAT){
					dataObj[8] = "待审核";
				}else if(ce.getState().intValue() == Constant.CE_STATE_FAIL){
					dataObj[8] = "转账失败";
				}else if(ce.getState().intValue() == Constant.CE_STATE_NOPASS){
					dataObj[8] = "审核不通过";
				}else if(ce.getState().intValue() == Constant.CE_STATE_PASS){
					dataObj[8] = "审核通过";
				}else if(ce.getState().intValue() == Constant.CE_STATE_SUCCESS){
					dataObj[8] = "已转账";
				}
				datas.add(dataObj);
			}
			HssfUtil.writeHssf("提现表", columnNames, datas, filename, resp.getOutputStream());
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**驳回提现申请
	 * 
		 * @description	
		 * @author  han1088
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "authCashEx", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET, RequestMethod.POST })
	public String authCashEx(Integer state, String remark, String ids){
		Systemuser user = (Systemuser) RequestUtil.getSessionAttribute(Constant.CMS_SESSION_LOGIN_USER);
		List<Integer> idList = JSONArray.parseArray(ids, Integer.class);
		List<CashExtract> re = new ArrayList<CashExtract>();
		for(Integer id : idList){
			CashExtract data = cashExtractService.findCashExById(id);
			if(data == null){
				continue;
			}
			data.setEdittime(new Date());
			data.setRemark(remark);
			data.setState(Constant.CE_STATE_NOPASS);
			data.setAuthuserid(user.getUserid());
			cashExtractService.update(data);
			//驳回后恢复额度
			Wallet w = walletService.getWallet(data.getUserid());
			String taskId = data.getId().toString()+"="+Constant.CE_STATE_NOPASS;//提现申请的ID=状态
			billService.creatBill(null, w.getId(), data.getMoney()+1, 
					Constant.BILL_TYPE_CASH,"提现被驳回", taskId, null, Constant.CHARGE_CHANNEL_TRANSFER,
					user.getRealname());
			try {
				CashExtract ce = cashExtractService.getCashExtById(id);
				MsgHelp.sendCashNoPass(ce.getTel(), ce.getRealname());
			} catch (ClientException e) {
				e.printStackTrace();
			}
			re.add(data);
		}
		return new ResponseWrapTo(CodeType.success, "数据更新成功", re).toJson();
	}
	
	/**
	 * 
		 * @description	
		 * @author  han1088
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getAllCashExDetail", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET, RequestMethod.POST })
	public String getAllCashExDetail(Integer id){
		CashExtract data = cashExtractService.getCashExtById(id);
		String bankcard = data.getBankcard();
		data.setAreaModel(AreaHelp.getInstance().getAreaModels(data.getArea()));
		data.setBankcardtype(JSONObject.parseObject(bankcard).getString("bankcardtype"));
		data.setBankcardno(JSONObject.parseObject(bankcard).getString("bankcardno"));
		return new ResponseWrapTo(CodeType.success, "", data).toJson();
	}
	
	/**
	 * 
		 * @description	
		 * @author  han1088
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getAllCashExList", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET, RequestMethod.POST })
	public String getAllCashExList(String startDate, String endDate,Integer state, Integer sortType,
			Integer areaCode, String condition,Integer pageNo, String hotelName){
		Pager<CashExtract> data = cashExtractService.getAllCashExtByPage( startDate,  endDate, state,  sortType,
				 areaCode,  condition, pageNo, hotelName);
		return new ResponseWrapTo(CodeType.success, "", data).toJson();
	}
	
	@ResponseBody
	@RequestMapping(value = "getEmployyerDetailByTel", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET, RequestMethod.POST })
	public String getEmployyerDetailByTel(String tel){
		Employee data = emservice.findEmployeeByTel(tel);
		if(data == null){
			return new ResponseWrapTo(CodeType.fail, "未能查询到改帮工信息", null).toJson();
		}
		if(StringUtils.isNotBlank(data.getBankcard())){
			data.setBankcardno(JSONObject.parseObject(data.getBankcard()).getString("bankcardno"));
			data.setBankcode(JSONObject.parseObject(data.getBankcard()).getString("bankcode"));
			data.setBankcardtype(JSONObject.parseObject(data.getBankcard()).getString("bankcardtype"));
		}
		if(!StrUtil.isNullOrEmpty(data.getArea())){
			data.setAreaModel(AreaHelp.getInstance().getAreaModels(data.getArea()));
		}
		return new ResponseWrapTo(CodeType.success, "", data).toJson();
	}
	
	/**
	 * 
		 * @description	提交帮工审核结果
		 * @author  han1088
		 * @param emid
		 * @param state
		 * @param remark
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "submitEmAuthRemark", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET, RequestMethod.POST })
	public String submitEmAuthRemark(String usrid, String remark){
		Employee data = emservice.getEmployee(usrid);
		data.setRemark(data.getRemark()== null?"":data.getRemark()+";"+remark);
		emservice.update(data);
		return new ResponseWrapTo(CodeType.success, "审核备注已经提交", null).toJson();
	}
	
	/**
	 * 
		 * @description	提交帮工审核结果
		 * @author  han1088
		 * @param emid
		 * @param state
		 * @param remark
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "submitEmAuthResult", produces = "application/json;charset=UTF-8", method = {RequestMethod.GET, RequestMethod.POST })
	public String submitEmAuthResult(String userid, Integer state){
		Systemuser user = (Systemuser) RequestUtil.getSessionAttribute(Constant.CMS_SESSION_LOGIN_USER);
		String cmsuserid = user.getUserid();
		String logMsg = "";
		Employee data = emservice.getEmployee(userid);
		if(state.intValue() == Constant.USER_STATE_PASS){
			if(data.getLevel() == null){
				return new ResponseWrapTo(CodeType.fail, "不通过，帮工清洁等级不能为空", null).toJson();
			}
		}
		data.setState(state);
		emservice.update(data);
		if(state.intValue() == Constant.USER_STATE_NO_PASS.intValue()){
			logMsg ="未通过";
			try {
				//发送短信通知
				MsgHelp.sendAuthEmUserNoPass(data.getTel(), data.getRealname());
			} catch (ClientException e) {
				e.printStackTrace();
			}
		}
		if(state.intValue() == Constant.USER_STATE_PASS.intValue()){
			logMsg ="通过";
			try {
				MsgHelp.sendAuthEmUserPass(data.getTel(), data.getRealname());
			} catch (ClientException e) {
				e.printStackTrace();
			}
		}
		if(state.intValue() == Constant.USER_STATE_FREEZE.intValue()){
			logMsg ="冻结";
			try {
				MsgHelp.sendAuthUserStop(data.getTel(), data.getRealname(),Constant.USER_TYPE_EMPLOYEE);
			} catch (ClientException e) {
				e.printStackTrace();
			}
		}
		String host = RequestUtil.getRequest().getRemoteHost();
		Logger logger = new Logger(new Date(), cmsuserid, host,user.getRealname());
		String context="审核帮工资料:"+data.getRealname()+";审核结果："+logMsg;
		EmLogModel emm = new EmLogModel(Constant.logger.LOG_EM_AUTH,data.getUserid(), data.getRealname(), context);
		logManager.creatEmLog(emm, logger);	
		
		return new ResponseWrapTo(CodeType.success, "审核结果已经提交", null).toJson();
	}
	
	@ResponseBody
	@RequestMapping(value = "getEmployyerDetail", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET, RequestMethod.POST })
	public String getEmployyerDetail(String userid){
		Employee data = emservice.getEmployee(userid);
		/*try{
			JSONObject bankcard = JSONObject.parseObject(data.getBankcard());
			data.setBankcardno(bankcard.getString("bankcardno"));
			data.setBankcard(bankcard.getString("bankcardtype"));
		}catch(Exception e){
			data.setBankcardno("");
			data.setBankcard("");
		}*/
		if(!StrUtil.isNullOrEmpty(data.getArea())){
			data.setAreaModel(AreaHelp.getInstance().getAreaModels(data.getArea()));
		}
		return new ResponseWrapTo(CodeType.success, "", data).toJson();
	}
	
	@ResponseBody
	@RequestMapping(value = "getAllEmployyer", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET, RequestMethod.POST })
	public String getAllEmployyer(String startDate, String endDate,Integer state, Integer level
			, Integer areaCode, String condition,Integer pageNo, String hotelName, Integer sortType){
		Pager<Employee> data = emservice.findEmployee(startDate,endDate,state,level,areaCode,condition,pageNo,hotelName, sortType);
		return new ResponseWrapTo(CodeType.success, "", data).toJson();
	}
	
	@ResponseBody
	@RequestMapping(value = "expEmployyer", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET, RequestMethod.POST })
	public void expEmployyer(HttpServletResponse resp, HttpServletRequest req,String startDate, String endDate,Integer state, Integer level
			, Integer areaCode, String condition){
		List<Employee> data = emservice.expEmployee(startDate,endDate,state,level,areaCode,condition);
		String filename = "帮工.xls";
		resp.setHeader("Content-Type", "application/octet-stream");
		try {
			resp.setHeader("Content-Disposition", "attachment;filename=" + HssfUtil.buildAttachmentFileName(req, filename));
			List<Object[]> datas = new ArrayList<Object[]>();
			String[] columnNames = new String[] { "姓名","手机号","性别","年龄","所在地区","清洁等级","累计清洁房量","紧急联系人","紧急联系人电话号码","身份证号","银行名称","银行卡号","审核状态"};
			for(Employee em : data){
				Object[] dataObj = new Object[columnNames.length];
				dataObj[0] = em.getRealname();
				dataObj[1] = em.getTel();
				if(em.getSex() != null && em.getSex().intValue() == 1){
					dataObj[2] = "男";
				}else if(em.getSex() != null && em.getSex().intValue() == 2){
					dataObj[2] = "女";
				}
				dataObj[3] = em.getAge();
				
				String address = "";
				if(em.getArea() != null){
					AreaModel[] area = AreaHelp.getInstance().getAreaModels(em.getArea().toString());
					for(AreaModel a:area){
						address = address+a.getName();
					}
				}
				dataObj[4] = address;
				dataObj[5] = em.getLevel();
				dataObj[6] = em.getRoomcount();
				dataObj[7] = em.getEmergencyuser();
				dataObj[8] = em.getEmergencytel();
				dataObj[9] = em.getIdcard();
				if(StringUtils.isNotBlank(em.getBankcard())){
					dataObj[10] = JSONObject.parseObject(em.getBankcard()).getString("bankcardtype");
					dataObj[11] = JSONObject.parseObject(em.getBankcard()).getString("bankcardno");
				}else{
					dataObj[10] = "";
					dataObj[11] = "";
				}
				
				if(em.getState().intValue() == Constant.USER_STATE_CREAT.intValue()){
					dataObj[12] = "待审核";
				}else if(em.getState().intValue() == Constant.USER_STATE_FREEZE.intValue()){
					dataObj[12] = "已冻结";
				}else if(em.getState().intValue() == Constant.USER_STATE_NO_PASS.intValue()){
					dataObj[12] = "未通过审核";
				}else if(em.getState().intValue() == Constant.USER_STATE_PASS.intValue()){
					dataObj[12] = "通过审核";
				}
				datas.add(dataObj);
			}
			HssfUtil.writeHssf("帮工表", columnNames, datas, filename, resp.getOutputStream());
		}catch(Exception e){
			
		}
	}
	
	/**
	 *  tel 电话
		realname 姓名
		emergencyuser 工龄
		level 等级
		area 地区
		emergencyuser 紧急联系人
		emergencytel 紧急联系电话
		address 详细地址
		idcard 身份证号码
		bankcardtype 银行
		bankcardno 银行卡号
		 * @description	
		 * @author  han1088
		 * @param em
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "addEm", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET, RequestMethod.POST})
	public String addEm(Employee em){
		Systemuser user = (Systemuser) RequestUtil.getSessionAttribute(Constant.CMS_SESSION_LOGIN_USER);
		String userid = user.getUserid();
		if(StringUtils.isNotBlank(em.getBankcardno())){//客户端给了新的卡号
			//先置空后赋值
			em.setBankcard(null);
			TranxServiceImpl tranxService=new TranxServiceImpl();
			boolean isfront=false;//是否发送至前置机（由前置机进行签名）如不特别说明，商户技术不要设置为true
			Map<String, Object> data = tranxService.serchCardBin(TranxCon.tranURL, em.getBankcardno(), isfront, Constant.pfxPath, Constant.tltcerPath);
			int code = (int) data.get("code");
			if(code != 0){
				return new ResponseWrapTo(CodeType.fail, data.get("message").toString(), em).toJson();
			}
			em.setBankcode(data.get("bankcode").toString());
			em.setBankcardtype(data.get("bankname").toString());
		}else{
			if(StringUtils.isNotBlank(em.getBankcard())){
				em.setBankcardno(JSONObject.parseObject(em.getBankcard()).getString("bankcardno"));
				em.setBankcode(JSONObject.parseObject(em.getBankcard()).getString("bankcode"));
				em.setBankcardtype(JSONObject.parseObject(em.getBankcard()).getString("bankcardtype"));
				em.setBankcard(null);
			}
		}
		if(em.getUserid() != null){//更新资料
			em.setState(Constant.USER_STATE_CREAT);
			Map<String, String> bankCard = new HashMap<String, String>();
			bankCard.put("bankcardno", em.getBankcardno());
			bankCard.put("bankcardtype", em.getBankcardtype());
			bankCard.put("bankcode", em.getBankcode());
			/*boolean isfront=false;//是否发送至前置机（由前置机进行签名）如不特别说明，商户技术不要设置为true
			TranxServiceImpl tranxService=new TranxServiceImpl();
			try {
				Map<String,Object> re = tranxService.singleAcctVerify(TranxCon.tranURL, em.getRealname(), 
						em.getBankcardno(), em.getIdcard(), em.getBankcode(), isfront,Constant.pfxPath,Constant.tltcerPath);
				int code = (int) re.get("code");
				if(code == 0){
					em.setBankcard(JSONObject.toJSONString(bankCard));
				}else{
					Employee oldEm = emservice.getEmployee(em.getUserid());
					em.setBankcard(oldEm.getBankcard());
				}
			}catch(Exception e){
				
			}*/
			em.setBankcard(JSONObject.toJSONString(bankCard));
			emservice.update(em);
			String host = RequestUtil.getRequest().getRemoteHost();
			Logger logger = new Logger(new Date(), userid, host,user.getRealname());
			
			String context="修改帮工资料:"+em.getRealname();
			EmLogModel emm = new EmLogModel(Constant.logger.LOG_EM_EDIT,em.getUserid(), em.getRealname(), context);
			logManager.creatEmLog(emm, logger);	
			return new ResponseWrapTo(CodeType.success, "资料已经更新请等待审核", em).toJson();
		}
		if(em.getLevel() == null){
			em.setLevel(4);//默认4级
		}
		em.setUserid(UUIDUtils.getUUID()+"");
		em.setState(Constant.USER_STATE_CREAT);
		em.setCreattime(new Date());
		if(em.getBankcardno() != null){
			Map<String, String> bankCard = new HashMap<String, String>();
			bankCard.put("bankcardno", em.getBankcardno());
			bankCard.put("bankcardtype", em.getBankcardtype());
			bankCard.put("bankcode", em.getBankcode());
			em.setBankcard(JSONObject.toJSONString(bankCard));
		}
		emservice.save(em);
		//操作日志
		String host = RequestUtil.getRequest().getRemoteHost();
		Logger logger = new Logger(new Date(), userid, host,user.getRealname());
		
		String context="新增帮工:"+em.getRealname();
		EmLogModel emm = new EmLogModel(Constant.logger.LOG_EM_ADD,em.getUserid(), em.getRealname(), context);
		logManager.creatEmLog(emm, logger);	
		
		//创帮工钱包
		Wallet wallet = new Wallet();
		wallet.setUserid(em.getUserid());
		wallet.setUsertype(Constant.WALLET_USER_TYPE_EM);
		wallet.setState(Constant.WALLET_STATE_NOTACTIVE);
		wallet.setBalance(0f);
		wallet.setOverdraft(0f);
		walletService.save(wallet);
		return new ResponseWrapTo(CodeType.success, "资料已经保存请等待审核", em).toJson();
	}
	
	/**
	 * 
		 * @description	
		 * @author  han1088
		 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getEmCountGroupDate", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST, RequestMethod.GET })
	public String getEmCountGroupDate(){
		Map<String, Integer> data = emservice.getEmCount();
		return new ResponseWrapTo(CodeType.success, "", data).toJson();
	}
}
